const router = require("koa-router")();
const JWT = require('jsonwebtoken')
const { secret } = require('../config/keys')
const userList = [
  {
    username: "906446244@qq.com",
    password: "123456789",
    nickname: "噗嗤噗嗤",
    avator: "https://robohash.org/1231231?set=set3",
  },
  {
    username: "666666@qq.com",
    password: "987654321",
    nickname: "都分不清礼物看得起",
    avator: "https://robohash.org/3444?set=set4",
  },
];
router.post("/login", (ctx) => {
  // 1. 获取用户 密码
  const { username, password } = ctx.request.body;
  // 2. 查找
  const item = userList.find((v) => {
    return v.username === username && v.password === password;
  });
  // 3. 验证
  if (item) {
    // 存在
    ctx.body = {
      code: 10000,
      data: {
        ...item,
        token:  JWT.sign(item, secret)
      },
      message: "登录成功， 欢迎用户 " + item.nickname,
    };
  } else {
    // 不存在
    ctx.body = {
      code: 40004,
      message: "账户密码错误， 请重新登录",
    };
  }
});

router.get('/user/info', ctx => {
  // 获取 token
  const { token } = ctx.request.query;
  if(!token) {
    ctx.body = {
      code: 40001,
      message: 'token 不存在'
    }
  } else {
    // 解析 token  XXX
    try {
      const user = JWT.verify(token, secret);
      ctx.body = {
        code: 10000,
        message: 'ok',
        data: {
          ...user
        }
      }
    } catch {
      ctx.body = {
        code: 40003,
        message: '非法token， 请重新登录'
      }
    }
  }
})

module.exports = router;
